package com.api.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.api.dao.RoleModulesDao;
import com.api.entity.Modules;
import com.api.entity.RoleModules;
import com.api.entity.TreeDto;
import com.api.service.RoleModulesService;

@Service
public class RoleModulesServiceImpl implements RoleModulesService{

	@Autowired
	private RoleModulesDao roleModulesDao;
	/**
	 * 获取指定角色id的模块信息
	 */
	public List<Modules> findAllByRid(String roleId) {
		return roleModulesDao.findAllByRid(roleId);
	}
	public List<TreeDto> changeTreeNode(String roleId) {
		//声明树节点集合
		List<TreeDto> listTree = new ArrayList<TreeDto>();
		List<Modules>  listModules = findAllByRid(roleId);
		for(Modules modules : listModules) {
			TreeDto tree = new TreeDto();
			tree.setId(modules.getId());
			tree.setTitle(modules.getName());
			tree.setHref(modules.getPath());
			tree.setPid(modules.getParentId());
			tree.setChecked(modules.isChecked());
			listTree.add(tree);
		}
		return listTree;
	}
//加载树形结构
	public List<TreeDto> loadTree(String roleId) {
		List<TreeDto> TreeNodes = changeTreeNode(roleId);
		//声明一个集合存储根节点
		List<TreeDto> rootTree =  new ArrayList<TreeDto>();
		//声明一个集合存储子节点根节点
		for(TreeDto tree:TreeNodes) {
			if(tree.getPid()==0) {
				//父节点等于0  将数据存储到根节点集合
				rootTree.add(getChildren(TreeNodes,tree));
			}
			
		}
		return rootTree;
	}
	//获取对应子节点
	public TreeDto  getChildren(List<TreeDto> rootList,TreeDto dto){
		List<TreeDto> childrenList = new ArrayList<TreeDto>();
		for(TreeDto tree:rootList) {
			if(tree.getPid()==dto.getId()) {
				if(dto.getChildren()==null) {
					dto.setChildren(childrenList);
				}
				dto.getChildren().add(getChildren(rootList,tree));
			}
		}
		return dto;
	}
	/**
	 * 保存指定的角色能够访问的所有功能模块到系统中
	 * 1 .清空该角色下的模块
	 * 2 .保存所给用户的模块
	 */
	
	// 1 .清空该角色下的模块
	public int deleteRoleModulesByRid(String rId) {
		return roleModulesDao.deleteRoleModulesByRid(rId);
	}
	// 2 .保存所给用户的模块
	public int addRoleModules(RoleModules rms) {
		return roleModulesDao.addRoleModules(rms);
	}
	/**
	 * 删除模块的时间 删除掉拥有该模快权限用户的此权限
	 */
	public int deleteAllModulesByid(String id) {
		return roleModulesDao.deleteAllModulesByid(id);
	}

}
